const fs = require('fs');
var unityList = [];
var unityPath;
readFile = () => {
  var config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
  unityPath = config.unityPath;
  const arr = fs.readdirSync(unityPath);
  arr.forEach((item) => {
    if (item.indexOf(".meta") == -1) {
      console.log(item);
      let d = fs.readFileSync(unityPath + "/" + item, "utf8");
      unityList.push(JSON.parse(d));
    }
  });
}

main = () => {
  readFile();
  for (var i = 0; i < unityList.length; i++) {
    var gridId = getGridId(unityList[i]);
    var p = setTileMapId(unityList[i],gridId);
    unityList[i][0].childIDs = unityList[i][0].childIDs.concat(p);
    fs.writeFile(unityPath+"/"+ unityList[i][0].Name+".json", JSON.stringify(unityList[i]), (err) => {
      if (err) {
        console.error(err);
      }
    });
  }
}
getGridId = (data)=>{
  for (var j = 0; j < data.length; j++) {
    if (data[j].Name == "Grid") {
      data[j].childIDs = [];
      return data[j].ID;
    }
  }
}
setTileMapId = (data,gridId)=>{
  var p = [];
  for (var j = 0; j < data.length; j++) {
    if (data[j].Name == "Wall" || data[j].Name == "Lava" || data[j].Name == "Spike"|| data[j].Name == "Water") {
        if(data[j].ParentId == gridId) {
          data[j].ParentId = 1;
          p.push(data[j].ID);
        }
    }
  }
  return p;
}
main();